package cn.liit.weixin.templatemsg.utils;

import java.util.Map;

import cn.liit.weixin.core.basic.accesstoken.AccessTokenSupport;
import name.zbq.bush.utils.http.HttpConnect;

public class MsgUtil {

	public static final String APIURL = "https://api.weixin.qq.com/cgi-bin/message/template/send?";
	/**
	 * @param accessToken
	 * @param openid 用户openid
	 * @param url 
	 * @param templateid 模板消息id
	 * @param first 内容标题
	 * @param keywords 内容关键字数组，keyword1,keyword2...keywordn
	 * @param remark 底部备注信息
	 * @return 调用返回结果     
	 * {
           "errcode":0,
           "errmsg":"ok",
           "msgid":200228332
       }
	 */
	public static Map<String,String> sendTemplateMsg(String accessToken,String openid,String url,String templateid,String first,String[] keywords,String remark) {
		StringBuilder sb = new StringBuilder();
		sb.append("{\"touser\":\""+openid+"\","
		+ "\"template_id\":\""+templateid+"\","
		+ "\"url\":\""+url+"\","
		+ "\"data\":{"
			+ "\"first\":{\"value\":\""+first+"\",\"color\":\"#173177\"},"
		);
		int i = 1;
		for(String keyword : keywords) {
			sb.append("\"keyword"+i+"\":{\"value\":\""+keyword+"\",\"color\":\"#173177\"},");
			i++;
		}
		sb.append("\"remark\":{\"value\":\""+remark+"\",\"color\":\"#000000\"}");
		sb.append("}}");
		System.out.println(sb.toString());
		Map<String,String> result = HttpConnect.getInstance().doPostJson(APIURL+"access_token="+accessToken, 
				sb.toString());
		return result;
	}
	
	public static void main(String[] args) {
		 
		Map<String, String> result = sendTemplateMsg("M-FuMF1IEkjccF7ytQKTNiOVbjYRvy_3nA3P5wjDgrRopjR73VU8IIUpQRB-m4ymRDd_LLJrcM5qKXDf2Hw6arLca8nwc9vJ_OrfWfW58V2kn0DQ3SnwHsIp8-QMfK6BPTJcAJAUYO",
				"o_AT_t-Ce79H6KkZxCEu1vpJ3hOI",
				"www.baidu.com",
				"Fg0WstUAsab5FKKazwcbSV8CW0vl_8oZefjo8ZoqLcU",
				"您好，您在微信公众号服务系统中有一条新消息",
				new String[]{"NO.101","2015.06.07"},
				"\\n请点击阅读。");
		System.out.println(result);
	}
}
